import os
import subprocess
from abc import abstractmethod

from moviepy.audio.io.AudioFileClip import AudioFileClip


# 执行命令
def sub_process(cmd):
    subprocess.call(cmd, shell=True)


# mp3 的长度
def get_mp3_duration(path):
    clip = AudioFileClip(path)
    duration = clip.duration
    clip.close()
    return duration


class Base:

    def __init__(self, root_input_path, root_output_path, width, height):
        self.input = root_input_path
        self.output = root_output_path
        self.temp = os.path.join(root_output_path, 'temp')
        self.width, self.height = width, height
        if not os.path.exists(self.temp):
            os.mkdir(self.temp)

    pass

    def real_path(self, path, dir_path=None):
        path = os.path.join(self.input if dir_path is None else dir_path, path)
        directory_path = os.path.dirname(path)
        if not os.path.exists(directory_path):
            os.makedirs(directory_path)
        return path

    # 返回指定目录的所有文件
    def list_files(self, path, suffix=None, dir_path=None):
        directory = self.real_path(path, dir_path)
        files = os.listdir(directory)
        if suffix:
            files = [x for x in files if x.endswith(suffix)]
        return files

    # 返回指定目录 多个后缀的的所有文件的集合
    def classify_files(self, path, suffix, dir_path=None):
        file_types = {}  # 用于存储分类后的文件
        directory = self.real_path(path, dir_path)
        # 遍历指定目录下的所有文件
        for filename in [x for x in os.listdir(directory) if x[-4:] in suffix]:
            file_path = os.path.join(directory, filename)
            file_ext = os.path.splitext(filename)[1]  # 获取文件扩展名
            # 如果扩展名不在文件类型字典中，则添加一个新的键值对
            if file_ext not in file_types:
                file_types[file_ext] = []

                # 将文件添加到对应的扩展名列表中
            file_types[file_ext].append(file_path)

        return file_types

        # 提取歌词

    @abstractmethod
    def init_lyrics(self, name):
        pass

    # 画背景
    @abstractmethod
    def draw_bg(self, name, duration):
        pass

    # 生成封面
    @abstractmethod
    def generate_cover(self, name, info):
        pass

    # 合并字墓
    @abstractmethod
    def merge_text(self, mp3filename, lrc):
        pass

    # 合并音乐
    @abstractmethod
    def merge_music(self, pic_name, mp3):
        pass

    # 开始合并 背景 音乐 歌词
    @abstractmethod
    def merge(self, pic_name, mp3, lrc):
        pass
